﻿/* $RCSFile: RadWSCombo.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/WebControls/RadWSCombo.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:30  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;
using System.Collections;
using System.Data;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Security;

using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.UI.WebControls
{

    public enum WSEntity { none=0,systemuser,account,contact,lead,product,salesorder,quote,invoice,opportunity,activity,incident,task,phonecall,email,
                                letter,appointment,discounttype,list,kbarticle,contract,pricelevel,territory,transactioncurrency,uom,uomschedule,annotation,
                                campaignactivity,campaignresponse,businessunit,campaign,serviceappointment,queue,savedquery,userquery,
                                AccountMailTemplate,ContactMailTemplate,LeadMailTemplate,OrderMailTemplate};

    [ToolboxData("<{0}:RadWSCombo runat='server'></{0}:RadWSCombo>")]
    public class RadWSCombo : RadComboBox
    {

        public int PortalID                     =   -1;

        const string strWebServiceMethod        =   "WebServiceMethod";
        public string WebServiceMethod
        {
            get
            {
                object ob                       =   ViewState[strWebServiceMethod];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
            }
            set
            {
                ViewState[strWebServiceMethod]  =   value;
            }
        }

        const string strWebServicePath          =   "WebServicePath";

        public string WebServicePath
        {
            get
            {
                object ob                       =   ViewState[strWebServicePath];
                if ( ob != null )
                    return (string)ob;
                return string.Empty;
            }
            set
            {
                ViewState[strWebServicePath]   =   value;
            }
        }
        

        const string strWebServiceEntity          =   "WebServiceEntity";
        public WSEntity WebServiceEntity
		{
            get
            {
                object ob                       =   ViewState[strWebServiceEntity];
                if ( ob != null )
                    return (WSEntity)ob;
                return WSEntity.none;
            }
            set
            {
                WSEntity entName        =   value;
                if ( entName == WSEntity.systemuser )
                    WebServiceMethod    =   "GetSyStemUsers";
                else if ( entName == WSEntity.account )
                    WebServiceMethod    =   "GetAccounts";
                else if ( entName == WSEntity.contact )
                    WebServiceMethod    =   "GetContacts";
                else if ( entName == WSEntity.lead )
                    WebServiceMethod    =   "GetLeads";
                else if ( entName == WSEntity.product )
                    WebServiceMethod    =   "GetProducts";
                else if ( entName == WSEntity.salesorder )
                    WebServiceMethod    =   "GetOrders";
                else if ( entName == WSEntity.quote )
                    WebServiceMethod    =   "GetQuotes";
                else if ( entName == WSEntity.invoice )
                    WebServiceMethod    =   "GetInvoices";
                else if ( entName == WSEntity.opportunity )
                    WebServiceMethod    =   "GetOpportunities";
                else if ( entName == WSEntity.activity )
                    WebServiceMethod    =   "GetActivities";
                else if ( entName == WSEntity.incident )
                    WebServiceMethod    =   "GetIncidents";
                else if ( entName == WSEntity.task )
                    WebServiceMethod    =   "GetTasks";
                else if ( entName == WSEntity.phonecall )
                    WebServiceMethod    =   "GetPhoneCalls";
                else if ( entName == WSEntity.email )
                    WebServiceMethod    =   "GetEMails";
                else if ( entName == WSEntity.letter )
                    WebServiceMethod    =   "GetLetters";
                else if ( entName == WSEntity.appointment )
                    WebServiceMethod    =   "GetAppointments";
                else if ( entName == WSEntity.discounttype )
                    WebServiceMethod    =   "GetDiscountTypes";
                else if ( entName == WSEntity.list )
                    WebServiceMethod    =   "GetLists";
                else if ( entName == WSEntity.kbarticle )
                    WebServiceMethod    =   "GetKbArticles";
                else if ( entName == WSEntity.contract )
                    WebServiceMethod    =   "GetContracts";
                else if ( entName == WSEntity.pricelevel )
                    WebServiceMethod    =   "GetPriceLevels";
                else if ( entName == WSEntity.territory )
                    WebServiceMethod    =   "GetTerritories";
                else if ( entName == WSEntity.transactioncurrency )
                    WebServiceMethod    =   "GetCurrencies";
                else if ( entName == WSEntity.uom )
                    WebServiceMethod    =   "GetUnits";
                else if ( entName == WSEntity.uomschedule )
                    WebServiceMethod    =   "GetUnitFamilies";
                else if ( entName == WSEntity.annotation )
                    WebServiceMethod    =   "GetAnnotations";
                else if ( entName == WSEntity.campaignactivity )
                    WebServiceMethod    =   "GetCampaignActivities";
                else if ( entName == WSEntity.campaignresponse )
                    WebServiceMethod    =   "GetCampaignResponses";
                else if ( entName == WSEntity.businessunit )
                    WebServiceMethod    =   "GetBusinessUnits";
                else if ( entName == WSEntity.campaign )
                    WebServiceMethod    =   "GetCampaigns";
                else if ( entName == WSEntity.serviceappointment )
                    WebServiceMethod    =   "GetServiceAppointments3";
                else if ( entName == WSEntity.queue )
                    WebServiceMethod    =   "GetQueues";
                else if ( entName == WSEntity.savedquery )
                    WebServiceMethod    =   "GetSavedQueries";
                else if ( entName == WSEntity.userquery )
                    WebServiceMethod    =   "GetUserQueries";
                else if ( entName == WSEntity.ContactMailTemplate )
                    WebServiceMethod    =   "GetContactMailTemplates";
                else if ( entName == WSEntity.LeadMailTemplate )
                    WebServiceMethod    =   "GetLeadMailTemplates";
                else if ( entName == WSEntity.OrderMailTemplate )
                    WebServiceMethod    =   "GetOrderMailTemplates";
                else if ( entName == WSEntity.AccountMailTemplate )
                    WebServiceMethod    =   "GetAccountMailTemplates";
                else 
                {
                    const string msg0   =   "[E]RadWSCombo WebServiceEntity SET bad entity name '{0}'";
                    string msg          =   string.Format(CultureInfo.InvariantCulture,msg0,entName);
                    if ( DataTypeTraceSwitch.Sw.TraceError )
                        Trace.WriteLine( msg,DataTypeTraceSwitch.Sw.Info);
                    throw new ArgumentException(msg);
                }
                ViewState[strWebServiceEntity]  =   entName;
                WebServicePath                  =   "/Services/CrmEntities.asmx";
            }
		}
        
        
        /// <summary>
        /// Combobox filled by web service
        /// </summary>
        public RadWSCombo()
        {
            if ( HttpContext.Current == null )
                return;
            PortalSettings portalSettings   =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
            PortalID                        =   portalSettings.PortalID;
        }

        /// <summary>
        /// Combobox filled by web service second ctor
        /// </summary>
        public RadWSCombo(string wwebServiceMethod,string wwebServicePath) 
        {

            WebServiceMethod                =   wwebServiceMethod;
            WebServicePath                  =   wwebServicePath;
            if ( HttpContext.Current == null )
                return;
            PortalSettings portalSettings   =   (PortalSettings)HttpContext.Current.Items[StStr.strPortalSettings];
            PortalID                        =   portalSettings.PortalID;
        }

        protected virtual string makeScript(string nm)
        {
            StringBuilder sb  =     new StringBuilder();
            sb.AppendFormat("function {0}(sender, args)\n{{",nm);
            sb.Append("var context = args.get_context();context[\"FilterString\"] = args.get_text();");
            sb.Append("}\n");
            sb.AppendFormat("function onDropDownOpening{0}(sender, args)\n{{",nm);
            sb.Append("sender.requestItems(sender.get_text(), false);");
            sb.Append("}\n");

            string src          =   sb.ToString();
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadWSCombo makeScript script={0}.",src),WebControlsTraceSwitch.Sw.Info);
            return src;
        }

        override protected void OnInit(EventArgs e)
        {
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadWSCombo OnInit BEG IsPostBack: {0}", Page.IsPostBack), WebControlsTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RadWSCombo OnInit END.", WebControlsTraceSwitch.Sw.Info);
        }
        protected virtual string makeScriptName()
        {
            return string.Format("OnClientItemsRequesting_{0}", ClientID);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]RadWSCombo OnPreRender BEG IsPostBack: {0}", Page.IsPostBack), WebControlsTraceSwitch.Sw.Info);
            string nm                   =   makeScriptName();
            OnClientItemsRequesting     =   nm;
            if ( Items.Count > 0 )
                OnClientDropDownOpening =   string.Format("onDropDownOpening{0}",nm);
            ((ADNPage)Page).RegisterADNClientScriptBlock(GetType(), nm, makeScript(nm), true);
            base.OnPreRender(e);
            if (WebControlsTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]RadWSCombo OnPreRender END.", WebControlsTraceSwitch.Sw.Info);
        }

        
        protected virtual void InitializeComponent()
        {
            WebServiceSettings.Method   =   WebServiceMethod;
            WebServiceSettings.Path     =   WebServicePath;
            EnableLoadOnDemand          =   true;
        }

    }
}
